const ws = require('nodejs-websocket')
let roomMgr = require('./roomMgr')
//负责登陆服务器消息管理的模块
class PSZMessageMgr{
    constructor() {

    }
    static getInstance() {
        if(!PSZMessageMgr.instance){
            PSZMessageMgr.instance = new PSZMessageMgr();
            return PSZMessageMgr.instance;
        }else{
            return PSZMessageMgr.instance;
        }
    }
    //创建服务并监听  port-> 端口号
    createServer(port){
        let websocket =  ws.createServer((client)=>{
            client.on('text',(result)=>{
                console.log('客户端发来了消息:',result);
                let message = JSON.parse(result);
                let type = message.type;
                let data = message.data;
                this.recvMessaage(type,data,client);
                console.log('PSZ游戏服务器接收到消息；消息类型->',type,'，数据为->',data);
            })
            client.on('error',(err)=>{
                console.log('连接出现错误',err)
            })
            client.on('close',()=>{
                console.log('连接断开');
            })
        })
        websocket.listen(port);
        console.log('PSZ游戏服务器启动，端口号为：',port);
    }
    //接收客户端消息并处理 type--消息类型  data--传递的数据  client--某个客户端
    recvMessaage(type,data,client){
        switch(type){
            case 'request_room_info':
                console.log('客户端发来login消息');
                this.onRequestRoomInfo(type,data,client);
                break;
            default:
                break;
        }
    }

    sendMessage(type,data,client){
        let result = {
            type:type,
            data:data,
        }
        client.send(JSON.stringify(result));
    }

    onRequestRoomInfo(type,data,client){
        //data = { roomID: '917567', userID: 666666 }
        console.log('请求房间信息数据是',type,data);

        let roomIsExist = false;//判断roomMgr里面有没有我们请求的房间信息
        if(roomMgr.getInstance()._roomList.length == 0){
            roomIsExist = true;
            global.PSZServerMgr.PSZDbMgr.getRoomInfo(data.roomID).then((result)=>{
                let roomData = result[0];
                roomMgr.getInstance().createRoom(type,roomData,client);
                console.log('游戏从数据库中查询到房间信息并创建');
            }).catch((err)=>{
                console.log('查询房间信息出错，错误原因：',err);
            })
        }else{
            for (let i = 0; i < roomMgr.getInstance()._roomList.length; i++) {
                let tmpRoom = roomMgr.getInstance()._roomList[i];
                if(tmpRoom.roomID == data.roomID){
                    //说明在房间列表查询到房间信息，则不需要在数据中获取，直接返回即可
                    roomIsExist = true;
                    global.PSZServerMgr.PSZMessageMgr.sendMessage(type,tmpRoom.getRoomInfo(),client);
                    tmpRoom.addPlayer(data.userID,client);
                    //待实现
                }
            }

        }

        //没有这个房间信息的情况下 roomIsExist = false；
        if(!roomIsExist){

        }
    }
}
global.PSZServerMgr.PSZMessageMgr = PSZMessageMgr.getInstance();
module.exports = PSZMessageMgr;
